#include "Configure.h"

Configure::Configure()
{

}

int32 Configure::Load(std::string confFile)
{
    if(confFile.size() <= 0)
    {
        WriteLog(FATAL, "ConfFile can't be empty.");
        return -1;
    }


    FILE* fd = fopen(confFile.c_str(), "r");

    if (fd == NULL)
    {
        WriteLog(FATAL, "Open conf[%s] failed.", confFile.c_str());
        return -1;
    }

    int32 ret = 0;
    int32 bufSize = 1000;
    char* lineBuf = new char[bufSize];

    while(!feof(fd))
    {

        if(fgets(lineBuf, bufSize, fd) == NULL)
        {
            continue;
        }

        std::string str = trim(std::string(lineBuf), " \r\n");
        if (str.size() <= 0 || str[0] == '#')
        {
            continue;
        }

        size_t idx;
        std::string delim = ":";
        if((idx = str.find(delim)) == std::string::npos)
        {
            continue;
        }

        std::string key = trim(str.substr(0, idx), " ");
        std::string value = trim(str.substr(idx + delim.length()), " ");
        if (key.size() > 0 && value.size() > 0)
        {
            _params[key] = value;
        }
    }

    delete [] lineBuf;

    return ret;
}

std::string Configure::GetStr(std::string key, std::string defaultValue)
{
    if(key.size() <= 0)
    {
        return defaultValue;
    }

    std::string temp;
    if(_params.find(key.c_str()) == _params.end())
    {
        return defaultValue;
    }

    return _params[key.c_str()];
}

int32 Configure::GetInt(std::string key, int32 defaultValue)
{
    if(key.size() <= 0)
    {
        return defaultValue;
    }

    if(_params.find(key.c_str()) == _params.end())
    {
        return defaultValue;
    }

    return atoi(_params[key.c_str()].c_str());
}
